<template>
    <PeInput ref="datePickerRef" v-model="date" :id="id" :prefixIcon="Calendar" :size="size" :placeholder="placeholder"
        :name="name" :disabled="disabled" :clearable="clearable" style="width: 200px;" @focus="focus" @blur="blur" />
    <Popup v-model="show" ref="popupRef">
        <DateCalendar :type="type" v-model:show="show" v-model:date="date" v-model:dateModel="dateModel"
            :format="format" :value-format="valueFormat" />
    </Popup>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from "vue"
import DateCalendar from "../date-calendar/date-calendar.vue";
import PeInput from '../input/input.vue';
import Calendar from "../../icons/calendar.vue";
import Popup from "../popup/popup.vue";

// 组件绑定值
const dateModel = defineModel<string | Date | number>()
// 输入框绑定值
const date = ref<string>("")

/**
 * @param type 绑定值类型
 * @param disabled 是否禁用
 * @param size 组件尺寸
 * @param readonly 是否只读
 * @param placeholder 输入框占位文本
 * @param clearable 是否可清空
 * @param name 输入框name
 * @param format 显示在输入框中的格式
 * @param value-format 绑定值格式，只有type='datestr'才有效
 * @param id 输入框id
 */
interface Props {
    type?: 'datestr' | 'date' | 'timestamp',
    disabled?: boolean,
    size?: 'default' | 'large' | 'small',
    readonly?: boolean,
    placeholder?: string,
    clearable?: boolean,
    name?: string,
    format?: string,
    valueFormat?: string,
    id?: string
}

withDefaults(defineProps<Props>(), {
    type: "datestr",
    disabled: false,
    size: 'default',
    readonly: false,
    clearable: true,
    format: "YYYY-MM-DD",
    valueFormat: "YYYY-MM-DD"
})

const emits = defineEmits(['focus', 'blur', 'change'])

watch(dateModel, newDate => {
    emits("change", newDate)
})

// 选择框元素
const datePickerRef = ref<any>()
const popupRef = ref<any>()

onMounted(() => {
    popupRef.value.setRef(datePickerRef.value)
})

// 下拉框显示标志
const show = ref<boolean>(false)

// 获取焦点
const focus = () => {
    show.value = true
    emits("focus")
}

// 失去焦点
const blur = () => {
    emits("blur")
}
</script>

<script lang="ts">
export default {
    name: "pe-date-picker"
}
</script>
